// https://www.lintcode.com/problem/reverse-linked-list-ii/description

/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: ListNode head is the head of the linked list 
     * @param m: An integer
     * @param n: An integer
     * @return: The head of the reversed ListNode
     */
     
    ListNode * reverseList(ListNode * head)
    {
        ListNode * pre = NULL;
        while (head)
        {
            ListNode * tmp = head->next;
            head->next = pre;
            pre = head;
            head = tmp;
        }
        return pre;
    }
    
    ListNode * findKth(ListNode * head, int k)
    {
        while(k--)
        {
            if (!head) return head; // 注意！
            head = head->next;
        }
        return head;
    }
    
    ListNode * reverseBetween(ListNode * head, int m, int n) {
        ListNode * dummy = new ListNode(-1);
        dummy->next = head;
// 要用dummy
// Input
// 5->null
// 1
// 1
// Expected
// 5->null
        ListNode * pre = findKth(dummy, m - 1);
        ListNode * begin = pre->next;
        ListNode * end = findKth(dummy, n);
        ListNode * fut = end->next;
        end -> next = NULL;
        pre->next = reverseList(begin);
        begin->next = fut;
        return dummy->next;
    }
};